package com.electron.power.aio.mod.client;

import java.nio.ByteBuffer;

import org.smartboot.socket.Protocol;
import org.smartboot.socket.transport.AioSession;
import org.springframework.stereotype.Component;

import com.electron.power.model.mod.ModRoot;
import com.electron.power.model.mod.ModStr;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class ClientStrProtocol implements Protocol<String> {

	@Override
	public String decode(ByteBuffer byteBuffer, AioSession<String> session) {
		try {

			int length = byteBuffer.getInt(byteBuffer.position());
			if (length + 4 < byteBuffer.remaining()) {
				return null;
			}
			 byte[] b = new byte[byteBuffer.getInt()];//3        
			 byteBuffer.get(b);//4       
			 String readValue = new String(b);
			 return readValue;
		} catch (Exception e) {
			log.error("错误", e);
			byteBuffer.reset();
			return null;
		}
	}

	public ByteBuffer encode(ModStr msg, AioSession<ModStr> session) {
		try {
			int frameLength = ModRoot.getFrameLenth() * 2;
			ByteBuffer byteBuffer = ByteBuffer.allocate(frameLength);
			// ByteBuffer byteBuffer = ByteBuffer.allocate(500);
			byteBuffer.put(
					"550300661A2B3C4D5E8000000000000000000000000000000000000003E70000000000000CE40000138800000000000000000000000000000000000003E70000000000000CFD0000138800000000000000000000000000000000000003E70000000000000C99000013887252"
							.getBytes());
			// b.putInt(s);
//			byteBuffer.rewind();
			byteBuffer.flip();
			return byteBuffer;
		} catch (Exception e) {
			log.error("写数据错误", e);
			return null;
		}
	}

	public static void main(String[] args) {
		String s = "5530661A2B3C4D5E80000000000000000A003E7000900CFD001388000000000000000A003E7000900CFD001388000000000000000A003E7000900C80001388C484";
		System.out.println(s.length());
		System.out.println(ModRoot.getFrameLenth() * 2);
	}

}
